from flask import Flask
from flask_restful import Resource, Api, reqparse

from typing import Dict

app = Flask(__name__)
api = Api(app)


class User:
    """
    用户实体类
    """
    id: int
    name: str

    def __init__(self, u_id, name):
        self.id = u_id
        self.name = name

    def __repr__(self):
        return f"User{{id={self.id} , name='{self.name}'}}"

    def todict(self):
        return {self.id: self.name}


# 字典容器，保存所有的user对象
userMap: Dict[int, User] = dict()

# 传入参数解析
parser = reqparse.RequestParser()
parser.add_argument('id', type=int, required=True, location='form')
parser.add_argument('name', type=str, required=True, location='form')


@api.resource('/')
class UserListView(Resource):
    """
    列表api，没有路由参数
    """

    def get(self):
        return str(userMap)

    def post(self):
        param = parser.parse_args()
        p_id = param.get('id')
        if p_id in userMap:
            return f"已经存在id={p_id}的user对象，无法新增"
        else:
            p_name = param.get('name')
            user = User(p_id, p_name)
            userMap.update({p_id: user})
            return str(userMap)


@api.resource('/<int:u_id>')
class UserView(Resource):
    """
    单个元素api，需要有路由参数u_id，以指定要操作的user对象id
    """

    def get(self, u_id: int):
        """
        获取一个user对象，对应get方法
        :param u_id: 要获取的用户id
        """
        if u_id in userMap:
            return str(userMap[u_id])
        else:
            return f"没有id={u_id}的user对象"

    def put(self, u_id: int):
        """
        修改，对应put方法
        :param u_id: 要修改的用户id
        """
        # 格式化传入参数
        param = parser.parse_args()
        if u_id in userMap:
            userMap[u_id].name = param.get('name')
            return str(userMap[u_id])
        else:
            return f"没有id={u_id}的user对象，无法修改"

    def delete(self, u_id: int):
        """
        删除一个user对象
        :param u_id: 要删除的用户对象id
        """
        if u_id in userMap:
            user = userMap[u_id]
            del userMap[u_id]
            return str(user)
        else:
            return f"没有id={u_id}的user对象，无法删除"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
